<?php

declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: hrenj
 * Date: 2018/7/6
 * Time: 10:29
 */

/**
 * 部署环境
 *
 * @return bool
 */
function prod()
{
    return env('APP_ENV', 'local') === 'production';
}

//计算字符串的长度(包括中英数字混合情况)
function countStringLen($str)
{
    $name_len = strlen($str);
    $temp_len = 0;
    for ($i = 0; $i < $name_len;) {
        if (strpos('abcdefghijklmnopqrstvuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', $str[$i]) === false) {
            $i = $i + 3;
            ++$temp_len;
        } else {
            $i = $i + 1;
            ++$temp_len;
        }
    }

    return $temp_len;
}

//统计汉字字符长度
function getChineseLength($str = '')
{
    if (empty($str)) {
        return 0;
    }
    $str2br = nl2br($str);
    //获取换行符出现的次数
    $br_num = substr_count($str2br, '
');
    //回车的长度
    $br_le = mb_strlen(nl2br('
'), 'UTF-8');

    //去除回车的长度
    $l = mb_strlen($str2br, 'UTF-8') - $br_num * $br_le;

    //加上一行的默认字数
    return $l + $br_num * 18;
}

/**
 * 获取被赋值的key value
 *
 * @param array $variables      变量名数组
 * @param array $variableValues 变量和值数组
 *
 * @return array
 *
 * @author yanghuichao
 *
 * @todo laravel 已经有了 helpers
 */
function getAssignedVariables($variables, $variableValues)
{
    $assigned = [];
    foreach ($variables as $variable) {
        if (isset($variableValues[$variable])) {
            $assigned[$variable] = $variableValues[$variable];
        }
    }

    return $assigned;
}

/**
 * 检验数组是否包含某些key，或某些key是否被赋值
 *
 * @param array $array    要检验的数组
 * @param array $keys     要检验的key
 * @param bool  $assigned key是否必须被赋值
 *
 * @return bool
 *
 * @author yanghuichao
 *
 * @todo laravel 已经有了 helpers
 */
function arrayHas($array, $keys, $assigned = false)
{
    if (!$array) {
        return false;
    }
    foreach ($keys as $key) {
        if (!isset($array[$key])) {
            return false;
        }
        if ($assigned && (null === $array[$key])) {
            return false;
        }
    }

    return true;
}

/*
 * 计算两个日期相隔的时间
 * @param datetime $date1 起始时间
 * @param datetime $date2 结束时间
 * @return array
 * */
function diffDate($date1, $date2)
{
    $datestart = date('Y-m-d', strtotime($date1));
    if (strtotime($datestart) > strtotime($date2)) {
        $tmp       = $date2;
        $date2     = $datestart;
        $datestart = $tmp;
    }
    [$Y1, $m1, $d1] = explode('-', $datestart);
    [$Y2, $m2, $d2] = explode('-', $date2);
    $Y              = $Y2 - $Y1; // 1
    $m              = $m2 - $m1; // 0
    $d              = $d2 - $d1; // -11
    if ($d < 0) {
        $d += (int) date('t', strtotime("-1 month $date2"));
        $m = --$m;
    }
    if ($m < 0) {
        $m += 12;
        $Y = --$Y;
    }
    if ($date1 == $date2) {
        $d = 1;
    }

    return ['year' => $Y, 'month' => $m, 'day' => $d];
}

/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 *
 * @param string $date1
 * @param string $date2
 *
 * @return number
 */
function diffDays($date1, $date2)
{
    if ($date1 > $date2) {
        $startTime = strtotime($date1);
        $endTime   = strtotime($date2);
    } else {
        $startTime = strtotime($date2);
        $endTime   = strtotime($date1);
    }
    $diff = $startTime - $endTime;
    $day  = $diff / 86400;

    return intval($day);
}

/**
 * 根据时间戳获取简短时间
 *
 * @param $timestamp
 *
 * @return false|string
 */
function showShortTime($timestamp)
{
    $s = time() - $timestamp;
    if ($s > 604800) {        //大于一周
        return date('m-d', $timestamp);
    } elseif ($s > 86400) {    //大于一天
        $week = ['', '1', '2', '3', '4', '5', '6', '7'];

        return $week[intval($s / 86400)] . '天前';
    } elseif ($s > 3600) {    //大于一小时
        return intval($s / 3600) . '小时前';
    } elseif ($s > 1800) {
        return '30分钟前';
    } elseif ($s > 600) {
        return '10分钟前';
    } elseif ($s > 300) {
        return '5分钟前';
    } elseif ($s > 60) {
        return '1分钟前';
    } else {
        return '刚刚';
    }
}

/**
 * 根据时间戳
 *
 * @param $time
 *
 * @return int
 */
function getAge($time)
{
    $a     = date('Y-m-d', $time);
    $b     = date('Y-m-d');
    $date1 = date_create($a);
    $date2 = date_create($b);
    $diff  = date_diff($date1, $date2); //获取年

    return $diff->y;
}

/*
 * 返回图片服务器网络地址
 * @param string $imgPath 图片相对地址
 * @return string 图片绝对路径地址
 * */
function getImageWithHost($imgPath)
{
    if (!$imgPath) {
        return '';
    }
    if (strrpos($imgPath, 'group') === false) {
        $imgPath = env('HOST_IMG_URL') . '/' . $imgPath;
    } else {
        $imgPath = env('HOST_IMG_FDFS') . '/' . $imgPath;
    }

    return $imgPath;
}

/**
 * 下载远程文件到本地
 *
 * @param string $imgUrl   远程文件地址
 * @param string $filePath 本地文件目录
 *
 * @return string
 */
function catchImage($imgUrl, $filePath)
{
    //$client = new \GuzzleHttp\Client(['verify' => false]);
    $client = new \GuzzleHttp\Client(['verify' => false]);
    //$response = $client->get($imgUrl, ['save_to' => $localFile]);
    $response = $client->request('get', $imgUrl);
    //获取文件类型
    $fileType = $response->getHeader('Content-Type');
    $fileType = trim(strrchr($fileType[0], '/'), '/');
    $file     = $filePath . '/' . uniqid() . '.' . $fileType;

    file_put_contents($file, $response->getBody()->getContents());

    return $file;
}

function getArrayByKey($arrayName, $keys = []): array
{
    $newArray = [];
    foreach ($arrayName as $key => $value) {
        if (is_array($keys)) {
            $newVal = [];
            foreach ($keys as $field) {
                $newVal[$field] = $value[$field];
            }

            $newArray[] = $newVal;
        }
    }

    return $newArray;
}

function viewCount(int $views): string
{
    if ($views < 1000) {
        return $views;
    } elseif ($views < 10000) {
        return floor($views / 1000) . '000+';
    } elseif ($views < 100000) {
        return floor($views / 10000) . '0000+';
    } elseif ($views < 1000000) {
        return floor($views / 100000) . '00000+';
    } else {
        return '1000000+';
    }
}

/*
 * 阿拉伯数字转为汉字
 */
function numToWord($num)
{
    $chiNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    $chiUni = ['', '十', '百', '千', '万', '亿', '十', '百', '千'];

    $chiStr = '';

    $num_str = (string) $num;

    $count     = strlen($num_str);
    $last_flag = true; //上一个 是否为0
    $zero_flag = true; //是否第一个
    $temp_num  = null; //临时数字

    $chiStr = ''; //拼接结果
    if ($count == 2) {//两位数
        $temp_num = $num_str[0];
        $chiStr   = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num] . $chiUni[1];
        $temp_num = $num_str[1];
        $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
    } elseif ($count > 2) {
        $index = 0;
        for ($i = $count - 1; $i >= 0; $i--) {
            $temp_num = $num_str[$i];
            if ($temp_num == 0) {
                if (!$zero_flag && !$last_flag) {
                    $chiStr    = $chiNum[$temp_num] . $chiStr;
                    $last_flag = true;
                }
            } else {
                $chiStr = $chiNum[$temp_num] . $chiUni[$index % 9] . $chiStr;

                $zero_flag = false;
                $last_flag = false;
            }
            $index++;
        }
    } else {
        $chiStr = $chiNum[$num_str[0]];
    }

    return $chiStr;
}

/*
 * 替换资源地址中的token
 * @param string $url --图片地址
 * @param string $token --token
 * @return string --新的图片地址
 * */
function replaceResourceToken($url, $token)
{
    $pattern = '/(?<=access_token=).*(?=&)/';

    return preg_replace($pattern, $token, $url);
}

//处理图片url地址
function returnImage($pathFile)
{
    if (empty($pathFile)) {
        return '';
    }
    $pattern = '#(http|https)://(.*\\.)?.*\\..*#i';
    if (preg_match($pattern, $pathFile)) {//完整url
        return $pathFile;
    } else {
        //非url 本地文件是否存在
        $bool = Storage::disk('public')->exists($pathFile);
        if ($bool) {//为真， 返回本地域名拼接地址
            return Storage::disk('public')->url($pathFile);
        } else {//阿里云是否存在
            if (Storage::disk(config('admin.upload.disk'))->exists($pathFile)) {
                return Storage::disk(config('admin.upload.disk'))->url($pathFile);
            } else {
                return '';
            }
        }
    }
}

// 兼容旧图片地址
function oldImg($url)
{
    // 图片地址 <img src="/storage/{{ $order->items->product->order_image }}" alt="">
    if ($url) {
        $newUrl = returnImage($url);
        if (empty($newUrl)) {
            $newUrl = returnImage('/storage/' . $url);
        }

        return $newUrl;
    }
}

// 获取jssdk配置
function getJSSDKConfig($arr, $debug, $json, $url)
{
    if (!$url) {
        return response()->json(['status' => false, 'msg' => 'params error', 'data' => '']);
    }

    $app = app('wechat.official_account');
    $app->jssdk->setUrl($url);

    return $app->jssdk->buildConfig($arr, $debug, $json, $url);
}

// api返回标准
function showJsonResult($resCode = 200, $rspDesc = 'success', $data = [])
{
    if (!$data) {
        $data = (object) $data;
    }

    $result = [
        'code' => $resCode,
        'message' => $rspDesc,
        'data' => $data,
    ];

    //返回结果
    return response()->json($result);
}

/**
 * 对象转数组
 *
 * @param $array object
 *
 * @return array
 */
function objectToArray($array)
{
    if (is_object($array)) {
        $array = get_object_vars($array);
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = objectToArray($value);
        }
    }

    return $array;
}

/**
 * 记录exception日志
 */
function logException(Throwable $e, string $msg = '')
{
    $estr = sprintf('msg: %s file: %s line: %d', $e->getMessage(), $e->getFile(), $e->getLine());
    if ($msg) {
        $estr = $msg . ' ' . $estr;
    }
    \Illuminate\Support\Facades\Log::error('错误 ' . $estr);
}
